package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"zy4/api/request"
	"zy4/internal/dao"
	"zy4/internal/model"
)

func AddGift(c *gin.Context) {
	var req request.AddGiftReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	gift := model.Gifts{
		Name:    req.Name,
		Money:   req.Money,
		FileUrl: req.FileUrl,
	}
	if !dao.Create(&gift) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "数据库插入失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": gift,
	})
}

func UpdateGift(c *gin.Context) {
	var req request.UpdateGiftReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	gift := dao.GetGift(req.Id)
	if gift.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "礼物不存在",
			"data": nil,
		})
		return
	}
	update := model.Gifts{
		Id:      int64(req.Id),
		Name:    req.Name,
		Money:   req.Money,
		FileUrl: req.FileUrl,
	}
	if !dao.Update(&update) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "更新失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "成功",
		"code":    200,
		"data":    update,
	})
}

func RemoveGift(c *gin.Context) {
	var req request.RemoveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	gift := dao.GetGift(req.Id)
	if gift.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "礼物不存在",
			"data": nil,
		})
		return
	}
	if !dao.Delete(&gift) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"data": nil,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": nil,
		"msg":  "删除成功",
	})
}

func ManyGift(c *gin.Context) {
	var req []request.ManyGiftReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"data": err.Error(),
			"msg":  "验证失败",
		})
		return
	}
	for _, giftReq := range req {
		many := &model.Gifts{
			Name:    giftReq.Name,
			Money:   giftReq.Money,
			FileUrl: giftReq.FileUrl,
		}
		if !dao.Create(&many) {
			fmt.Println("添加失败")
		}
	}
}
